package com.example.autopera.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * @author Code_lemon
 * @version 2.0.0
 * @description TODO 网络请求工具类
 * @date 2024/10/25 10:44
 * @title HttpClientUtils
 */
@Slf4j
@Component
public class HttpClientUtils {

    private final CloseableHttpClient httpClient;

    public HttpClientUtils() {
        this.httpClient = HttpClients.createDefault();
    }

    /**
     * 执行GET请求
     *
     * @param url 请求的URL
     * @return 响应内容字符串
     * @throws IOException
     */
    public String sendGet(String url) throws IOException {

        // 创建GET请求
        HttpGet httpGet = new HttpGet(url);

        // 执行请求
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            // 获取响应实体
            HttpEntity entity = response.getEntity();

            // 将响应实体转换为字符串并返回
            return entity != null ? EntityUtils.toString(entity, "UTF-8") : null;
        }
    }

    /**
     * 执行POST请求
     *
     * @param url  请求的URL
     * @param json 请求的JSON内容
     * @return 响应内容字符串
     * @throws IOException
     */
    public String sendPost(String url, String json) throws IOException {

        // 创建POST请求
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        httpPost.setHeader("Content-Type", "application/json");

        // 设置请求体
        StringEntity stringEntity = new StringEntity(json);
        httpPost.setEntity(stringEntity);

        // 执行请求
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            // 获取响应实体
            HttpEntity entity = response.getEntity();

            // 将响应实体转换为字符串并返回
            return entity != null ? EntityUtils.toString(entity, "UTF-8") : null;
        }
    }


}
